#include "MainWidget.h"
#include "ui_MainWidget.h"
#include <QMessageBox>
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QFileDialog>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <iostream>
#include <string>
#include <memory>
#include "AESAlgorithm.h"

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);
    ui->dateTimeEditExpiration->setDateTime(QDateTime::currentDateTime());
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::on_toolButtonSelect_clicked()
{
    QString path = ui->lineEditPath->text().trimmed();
    if (path.isEmpty() || !QDir(path).exists()) {
        path = ".";
    }

    QString dir = QFileDialog::getExistingDirectory(this, "打开", path, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if (dir.isEmpty()) {
        return;
    }

    ui->lineEditPath->setText(dir);
}

void MainWidget::on_pushButtonEncrypt_clicked()
{
    QString text = ui->lineEditMac->text().trimmed();
    QString path = ui->lineEditPath->text().trimmed();
    QString strDateTime = ui->dateTimeEditExpiration->dateTime().toString("yyyy-MM-dd hh:mm:ss");
    if (text.isEmpty()) {
        QMessageBox::warning(this, "提示", "MAC不能为空!");
        return;
    }

    if (path.isEmpty() || !QDir(path).exists()) {
        QMessageBox::warning(this, "提示", "路径为空或目录不存在，请重新选择路径!");
        return;
    }

    text = text + "|" + strDateTime;
    QString fileName = path + "/license";
    QFile oFile(fileName);
    if (oFile.open(QIODevice::WriteOnly)) {
        std::string strOut = gAESAlgorithm->cbcEncrypt(text.toStdString(), "");
        if (strOut.empty()) {
            oFile.close();
            QMessageBox::warning(this, "提示", "加密失败!");
            return;
        }
        oFile.write(QByteArray::fromStdString(strOut));
    }
    oFile.close();
    QMessageBox::information(this, "提示", "加密成功!");
}

void MainWidget::on_pushButtonDecrypt_clicked()
{
    QString path = ui->lineEditPath->text().trimmed();
    QString fileName = path + "/license";
    if (!QFile::exists(fileName)) {
        QMessageBox::warning(this, "提示", "文件不存在，请重新选择路径!");
        return;
    }

    QFile oFile(fileName);
    if (oFile.open(QIODevice::ReadOnly)) {
        QByteArray ary = oFile.readAll();
        std::string outStr = gAESAlgorithm->cbcDecrypt(ary.toStdString(), "");
        if (outStr.empty()) {
            oFile.close();
            QMessageBox::warning(this, "提示", "解密失败!");
            return;
        }
        ui->textEditResult->setText(QString::fromStdString(outStr));
    }
    oFile.close();
    QMessageBox::information(this, "提示", "解密成功!");
}
